﻿
using System;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Net.Cache;
using System.Collections;
using System.Collections.Generic;
using System.Web;

namespace WebTools
{
    public class HttpHelper
    {
        /// <summary>
        /// 延迟毫秒数
        ///默认为1秒
        /// </summary>
        protected int defer = 1000;
        /// <summary>
        /// 与请求相关的cookie（用于保持session）
        /// </summary>
        public CookieContainer cookies = new CookieContainer();

        public HttpHelper()
        {
        }
        public string Post(string url, string postData, string referer = "")
        {
            WebResponse webResponse = doPost(url, postData, referer);
            return ResponseToString(webResponse);
        }
        public string Get(string url, string referer = "", Hashtable headers = null)
        {
            WebResponse webResponse = doGet(url, referer, headers);
            return ResponseToString(webResponse);
        }

        /// <summary>
        /// 发送Post类型请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">参数</param>
        /// <returns></returns>
        public WebResponse doPost(string url, string postData, string referer = "")
        {
            try
            {
                Thread.Sleep(this.defer);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                //webRequest.CookieContainer = this.cookies;
                webRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                webRequest.Method = "POST";
                if (!string.IsNullOrWhiteSpace(referer))
                {
                    webRequest.Referer = referer;
                }

                webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)";
                webRequest.Timeout = 5000;
                webRequest.KeepAlive = false;

                byte[] paramByte = Encoding.UTF8.GetBytes(postData); // 转化
                webRequest.ContentLength = paramByte.Length;
                //webRequest.ContentType = "application/x-www-form-urlencoded";
                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(paramByte, 0, paramByte.Length);    //写入参数
                newStream.Close();
                return webRequest.GetResponse();
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }
        //public WebResponse doPost(string url, string postData, string referer = "")
        //{
        //    try
        //    {
        //        Thread.Sleep(this.defer);
        //        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        //        //webRequest.CookieContainer = this.cookies;
        //        webRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
        //        webRequest.Method = "POST";
        //        if (!string.IsNullOrWhiteSpace(referer))
        //        {
        //            webRequest.Referer = referer;
        //        }

        //        webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)";
        //        webRequest.Timeout = 5000;
        //        webRequest.KeepAlive = false;

        //        byte[] paramByte = Encoding.UTF8.GetBytes(postData); // 转化
        //        webRequest.ContentLength = paramByte.Length;
        //        //webRequest.ContentType = "application/x-www-form-urlencoded";
        //        Stream newStream = webRequest.GetRequestStream();
        //        newStream.Write(paramByte, 0, paramByte.Length);    //写入参数
        //        newStream.Close();
        //        return webRequest.GetResponse();
        //    }
        //    catch (Exception ce)
        //    {
        //        throw ce;
        //    }
        //}

        /// <summary>
        /// 发送Get类型请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">参数</param>
        /// <returns></returns>
        public WebResponse doGet(string url, string referer = "", Hashtable headers = null)
        {
            try
            {
                //Thread.Sleep(1000);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                //webRequest.CookieContainer = this.cookies;
                webRequest.Method = "get";

                AddHeaders(webRequest, headers);

                if (!string.IsNullOrWhiteSpace(referer))
                {
                    webRequest.Referer = referer;
                }
                webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)";
                return webRequest.GetResponse();
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }

        private void AddHeaders(HttpWebRequest webRequest, Hashtable headers)
        {
            if (headers != null)
            {
                foreach (DictionaryEntry de in headers)
                {
                    webRequest.Headers.Add(de.Key.ToString(), de.Value.ToString());
                }
            }
        }
        /// <summary>
        /// 根据相应返回字符串
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public string ResponseToString(WebResponse response)
        {
            try
            {
                Encoding encoding = Encoding.Default;
                string ContentType = response.ContentType.Trim();
                if (ContentType.IndexOf("utf-8") != -1)
                    encoding = Encoding.UTF8;
                else if (ContentType.IndexOf("utf-7") != -1)
                    encoding = Encoding.UTF7;
                else if (ContentType.IndexOf("unicode") != -1)
                    encoding = Encoding.Unicode;

                StreamReader stream = new StreamReader(response.GetResponseStream(), encoding);
                string code = stream.ReadToEnd();
                stream.Close();
                response.Close();
                return code;
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }

        /// <summary>
        /// 根据相应返回字符串
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public string ResponseToStringWithGzip(WebResponse response)
        {
            try
            {
                Encoding encoding = Encoding.Default;
                string ContentType = response.ContentType.Trim().ToLower();
                if (ContentType.IndexOf("utf-8") != -1)
                    encoding = Encoding.UTF8;
                else if (ContentType.IndexOf("utf-7") != -1)
                    encoding = Encoding.UTF7;
                else if (ContentType.IndexOf("unicode") != -1)
                    encoding = Encoding.Unicode;
                else if (ContentType.IndexOf("gbk") != -1)
                    encoding = Encoding.GetEncoding("GBK");

                StreamReader stream;
                GZipStream gz = null;

                if (!string.IsNullOrEmpty(response.Headers["Content-Encoding"]) && response.Headers["Content-Encoding"].ToLower() == "gzip")
                {
                    gz = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
                    stream = new StreamReader(gz, encoding);
                }
                else
                {
                    stream = new StreamReader(response.GetResponseStream(), encoding);
                }
                string code = stream.ReadToEnd();
                stream.Close();
                if (gz != null)
                    gz.Close();
                response.Close();
                return code;
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }

        public static Dictionary<string, string> GerUrlQuery()
        {
            string query = HttpContext.Current.Request.Url.Query;
            if (query != "")
            {
                Dictionary<string, string> res = new Dictionary<string, string>();

                foreach (var keyValue in query.Substring(1).Split('&'))
                {
                    for (var i = 0; i < keyValue.Split('=').Length; i = i + 2)
                    {
                        res.Add(keyValue.Split('=')[i], keyValue.Split('=')[i + 1]);
                    }
                }
                return res;
            }
            return null;
        }

        #region 获取客户端请求参数值
        /// <summary>
        /// 获取客户端请求参数值，以string形式返回
        /// </summary>
        /// <param name="paramName">参数名称</param>
        /// <returns></returns>
        public static string GetRequestStr(string paramName)
        {
            string retStr = HttpContext.Current.Request.Form[paramName];
            if (retStr == null)
            {
                retStr = HttpContext.Current.Request.QueryString[paramName];
            }
            if (retStr == null)
            {
                return "";
            }
            return retStr;
        }
        #endregion
    }
}